//
//  SEGOtherCreateActivityDetailViewController.m
//  ExcellentHome
//
//  Created by 陈区 on 13-11-22.
//  Copyright (c) 2013年 陈区. All rights reserved.
//
#import "SEGUsersListViewController.h"
#import "ActivityDetailApplyNumberCell.h"
#import "ActivityDetailTotalMemberCell.h"
#import "ActivityDetailMessageCell.h"
#import "ActivityDetailDescCell.h"
#import "ActivityDetailCreaterCell.h"
#import "ActivityRequestModel.h"
#import "SEGCreateActivityViewController.h"
#import "SEGFriendDetailViewController.h"
#import "SEGOtherCreateActivityDetailViewController.h"
//#import "UIImageView+WebCache.h"

@interface SEGOtherCreateActivityDetailViewController ()

@property (nonatomic, retain) ActivityRequestModel* activityRequestModel;

@end

@implementation SEGOtherCreateActivityDetailViewController
@synthesize activityModel = m_ActivityModel;
@synthesize activityId;
@synthesize footerView;
@synthesize memberArray;

- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)loadView
{
    UIScreen* scr = [UIScreen mainScreen];
    CGRect appbounds = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height - kNavigationBarAndStatusBarHeight);
    UIView* mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, appbounds.size.width, appbounds.size.height)];

    CGRect tabbounds = CGRectMake(0, 0, appbounds.size.width, appbounds.size.height);
    m_tableView = [[UITableView alloc] initWithFrame:tabbounds style:UITableViewStylePlain];
    m_tableView.delegate = self;
    m_tableView.dataSource = self;
    m_tableView.backgroundView = nil;
    m_tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    m_tableView.backgroundColor = [UIColor clearColor];

    [m_tableView registerClass:[ActivityDetailCreaterCell class] forCellReuseIdentifier:kActivityDetailCreaterCellIdentifier];
    [m_tableView registerClass:[ActivityDetailDescCell class] forCellReuseIdentifier:kActivityDetailDescCellIdentifier];
    [m_tableView registerClass:[ActivityDetailMessageCell class] forCellReuseIdentifier:kActivityDetailMessageCellIdentifier];
    [m_tableView registerClass:[ActivityDetailTotalMemberCell class] forCellReuseIdentifier:kActivityDetailTotalMemberCellIdentifier];

    [mainView addSubview:m_tableView];

    footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, appbounds.size.width, 54)];
    finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    finishBtn.frame = CGRectMake(10, 5, CGRectGetWidth(footerView.bounds)-20, 44);

    [finishBtn addTarget:self action:@selector(btnJionActivityClicked:) forControlEvents:UIControlEventTouchUpInside];
    finishBtn.titleLabel.textColor = kColor_2;

    [finishBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [finishBtn setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
    [finishBtn setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
    [footerView addSubview:finishBtn];
    m_tableView.tableFooterView = footerView;

    self.view = mainView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    number = 1;
    // Do any additional setup after loading the view.

    [self showCustomNavigationBackButton];

    self.navigationController.navigationBarHidden = NO;

    self.title = @"详情";

    if ([self checkIsAttend]) { //已经报名

        footerView.hidden = YES;
        UIScreen* scr = [UIScreen mainScreen];

        m_tableView.frame = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height - kNavigationBarAndStatusBarHeight);
    }

    if ([[self.activityModel.issuePerson stringValue] isEqualToString:kAccountUserID]) {
        [self showCustomNavigationRightButtonWithTitle:@"编辑"
                                                 image:[UIImage imageWithContentsOfFile:SEGPicName(@"common_btn_navbar_right_nor")]
                                       hightlightImage:[UIImage imageWithContentsOfFile:SEGPicName(@"common_btn_navbar_right_pre.png")]];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [m_tableView reloadData];
}

- (void)addActivityData:(ActivityModel*)activityEntity
{
    if (self.activityModel != activityEntity) {

        self.activityModel = nil;
        self.activityModel = activityEntity;
    }

    // 请求活动详情
    //    [[BusinessManager sharedManager].activityEntityManager requestActivityDetailWithActivityID:self.activityModel.serviceId orGroupID:nil];
    [self.activityRequestModel requestActivityDetailWithId:[self.activityModel.serviceId stringValue] finished:^(id result, NSError* error) {
        [self dealWithActivityDetailDict:result];
    }];

    // 请求活动成员
    //    [[BusinessManager sharedManager].activityMemberEntityManager requestActivityMemberEntityListWithActivityID:self.activityModel.serviceId];
    [self.activityRequestModel requestActivityMemberListWithId:[self.activityModel.serviceId stringValue] finished:^(id result, NSError* error) {
        self.memberArray = result;
        [m_tableView reloadData];
    }];
}

- (void)addServiceId:(NSString*)serviceId
{
    self.activityId = serviceId;
    // 请求活动详情
    //    [[BusinessManager sharedManager].activityEntityManager requestActivityDetailWithActivityID:self.activityModel.serviceId orGroupID:nil];
    [self.activityRequestModel requestActivityDetailWithId:self.activityId finished:^(id result, NSError* error) {
        [self dealWithActivityDetailDict:result];
    }];

    // 请求活动成员
    //    [[BusinessManager sharedManager].activityMemberEntityManager requestActivityMemberEntityListWithActivityID:self.activityModel.serviceId];
    [self.activityRequestModel requestActivityMemberListWithId:self.activityId finished:^(id result, NSError* error) {
        self.memberArray = result;
        [m_tableView reloadData];
    }];
}

#pragma mark - tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([[self.activityModel.issuePerson stringValue] isEqualToString:kAccountUserID]) {
        return 7;
    }
    else {
        return 8;
    }
}

//每行的高度
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    switch (indexPath.row) {
    case 0:
        if (self.activityModel.pic1) {
            return 198;
        }
        else {
            return 44;
        }

        break;
    case 4:
        return 0;
        break;

    case 5:
        if ([[self.activityModel.issuePerson stringValue] isEqualToString:kAccountUserID]) {
            
            return [self.activityModel.desc boundingRectWithSize:CGSizeMake(200.0f, 10000.0f)
                                                         options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                      attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE]}
                                                         context:nil].size.height + 30.0f;
        }
        else {
            if ([self checkIsAttend] || [self checkIsStop]) { //已经报名 或 已过期
                return 0;
            }
            else {
                return 44;
            }
        }
        break;
    case 6:
        if ([[self.activityModel.issuePerson stringValue] isEqualToString:kAccountUserID]) {
            return 80;
        }
        else {
            if ([self.activityModel.desc boundingRectWithSize:CGSizeMake(200.0f, 10000.0f)
                                                      options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                   attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE]}
                                                      context:nil].size.height == 0) {
                return 0;
            }
            return [self.activityModel.desc boundingRectWithSize:CGSizeMake(200.0f, 10000.0f)
                                                         options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                      attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE]}
                                                         context:nil].size.height + 30.0f;
        }
        break;

    case 7:
        return 80;
        break;

    default:
        break;
    }
    return 44;
}
#pragma mark - tableview delegate
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    NSString* indentSt = [NSString stringWithFormat:@"cellsectionrow%ld", (long)indexPath.row];

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:indentSt];

    switch (indexPath.row) {
    case 0: {
        ActivityDetailCreaterCell* cell = [ActivityDetailCreaterCell cellWithTableView:tableView];
        cell.dataSource = self.activityModel;
        UIButton* iconBtn = cell.iconButton;
        [iconBtn addTarget:self action:@selector(btnSendMessageToFriendClicked:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
        break;
    }

    case 1: {
        ActivityDetailDescCell* cell = [ActivityDetailDescCell cellWithTableView:tableView];
        [cell setDesc:@"活动名称"];
        [cell setContent:self.activityModel.name];
        return cell;
        break;
    }

    case 2: {
        ActivityDetailDescCell* cell = [ActivityDetailDescCell cellWithTableView:tableView];
        [cell setDesc:@"参与人数"];
        [cell setContent:[NSString stringWithFormat:@"%@人", self.activityModel.activityNum]];
        return cell;
        break;
    }
    case 3: {
        ActivityDetailDescCell* cell = [ActivityDetailDescCell cellWithTableView:tableView];
        [cell setDesc:@"报名时间"];

        NSDate* beginDate = [SEGUtils dateFromString:self.activityModel.startDate withFormatString:kTimeFormatStringSec];
        NSDate* endDate = [SEGUtils dateFromString:self.activityModel.endDate withFormatString:kTimeFormatStringSec];
        NSString* bTime = [SEGUtils stringDateByFormatString:@"yyyy.MM.dd" withDate:beginDate];
        NSString* eTime = [SEGUtils stringDateByFormatString:@"MM.dd" withDate:endDate];
        [cell setContent:[NSString stringWithFormat:@"%@-%@", bTime, eTime]];

        return cell;
        break;
    }
    case 4: {
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentSt];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
        break;
    }
    case 5: {
        if ([[self.activityModel.issuePerson stringValue] isEqualToString:kAccountUserID]) { //自己创建的活动 留言
            ActivityDetailMessageCell* cell = [ActivityDetailMessageCell cellWithTableView:tableView];
            [cell setContent:self.activityModel.desc];
            return cell;
        }
        else { //别人创建的活动  报名人数
            //自己已经参加过 或者 已过期的活动 不显示报名人数
            if ([self checkIsAttend] || [self checkIsStop]) { //已经报名 或 已过期
                if (cell == nil) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentSt];
                    cell.accessoryType = UITableViewCellAccessoryNone;
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                }
                return cell;
            }
            else {
                ActivityDetailApplyNumberCell* cell = [ActivityDetailApplyNumberCell cellWithTableView:tableView];
                reduceButton = cell.reduceButton;
                [reduceButton addTarget:self action:@selector(reduceButtonAction:) forControlEvents:UIControlEventTouchUpInside];

                numberCount = cell.numberCount;
                numberCount.delegate = self;
                numberCount.text = [NSString stringWithFormat:@"%d", number];

                addButton = cell.addButton;
                [addButton addTarget:self action:@selector(addButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                return cell;
            }
        }
        break;
    }
    case 6: {
        if ([[self.activityModel.issuePerson stringValue] isEqualToString:kAccountUserID]) { //自己创建的活动 总人数
            ActivityDetailTotalMemberCell* cell = [ActivityDetailTotalMemberCell cellWithTableView:tableView];
            [cell setMemberArray:self.memberArray];
            for (UIView* subview in cell.memberView.subviews) {
                if ([subview isKindOfClass:[UIButton class]]) {
                    UIButton* iconbutton = (UIButton*)subview;
                    [iconbutton addTarget:self action:@selector(btnMemberButton:) forControlEvents:UIControlEventTouchUpInside];
                }
            }
            return cell;
        }
        else { //留言
            ActivityDetailMessageCell* cell = [ActivityDetailMessageCell cellWithTableView:tableView];
            [cell setContent:self.activityModel.desc];
            return cell;
        }
        break;
    }
    case 7: { // 总人数
        ActivityDetailTotalMemberCell* cell = [ActivityDetailTotalMemberCell cellWithTableView:tableView];
        [cell setMemberArray:self.memberArray];
        for (UIView* subview in cell.memberView.subviews) {
            if ([subview isKindOfClass:[UIButton class]]) {
                UIButton* iconbutton = (UIButton*)subview;
                [iconbutton addTarget:self action:@selector(btnMemberButton:) forControlEvents:UIControlEventTouchUpInside];
            }
        }
        return cell;
        break;
    }
    default:
        break;
    }
    return cell;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [numberCount resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - TextFiled Delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField*)textField
{
    number = 0;
    textField.text = nil;
    CGRect parentRect = [textField convertRect:textField.bounds toView:self.view];
    [m_tableView setContentOffset:CGPointMake(0, parentRect.origin.y / 2) animated:YES];

    return YES;
}

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{

    number = [[NSString stringWithFormat:@"%@%@", textField.text, string] intValue];
    if (number < 1 || number > 999) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"", @"")
                                                        message:NSLocalizedString(@"请输入1~999之间的数！", @"")
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                              otherButtonTitles:nil];
        [alert show];

        return NO;
    }
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }

    return YES;
}

#pragma mark - 按钮事件
// 点击发起人头像
- (void)btnSendMessageToFriendClicked:(UIButton*)sender
{
    SEGFriendDetailViewController* detailCtl = [[SEGFriendDetailViewController alloc] init];
    detailCtl.hidesBottomBarWhenPushed = YES;
    detailCtl.friendId = [self.activityModel.issuePerson stringValue];
    [self.navigationController pushViewController:detailCtl animated:YES];
}

// 点击参加活动的成员头像
- (void)btnMemberButton:(UIButton*)sender
{
    if (sender.tag == 7) { //更多
        SEGUsersListViewController* usersCtl = [[SEGUsersListViewController alloc] init];
        usersCtl.hidesBottomBarWhenPushed = YES;
        [usersCtl reviceData:self.memberArray];
        [self.navigationController pushViewController:usersCtl animated:YES];
    }
    else {
        SEGFriendDetailViewController* detailCtl = [[SEGFriendDetailViewController alloc] init];
        detailCtl.hidesBottomBarWhenPushed = YES;
        //        [detailCtl addFriendEntityData:[self.memberArray objectAtIndex:sender.tag]];
        detailCtl.friendId = [self.memberArray objectAtIndex:sender.tag].userId;
        [self.navigationController pushViewController:detailCtl animated:YES];
    }
}

// 停止报名／立即报名按钮
- (void)btnJionActivityClicked:(UIButton*)sender
{
    if ([[self.activityModel.issuePerson stringValue] isEqualToString:kAccountUserID]) { //自己创建的活动 停止报名
        NSString* groupId = [SEGUtils stringDateByFormatString:@"yyyyMMddHHmmssSSS" withDate:[NSDate date]];
        [self.activityRequestModel requestActivityStartOrStopWithId:[self.activityModel.serviceId stringValue] andGroupChatID:groupId finished:^(id result, NSError* error) {
            [self dealWithStopActivityResult:result];
        }];
    }
    else {
        //        [[BusinessManager sharedManager].activityEntityManager requestCheckActivityPersonNum:[self.activityModel.serviceId stringValue] withPersonNum:[NSString stringWithFormat:@"%d",number]];
        [self.activityRequestModel requestCheckActivityPersonNumWithId:[self.activityModel.serviceId stringValue] finished:^(id result, NSError* error) {
            [self dealWithCheckActivityPersonNumResult:result];
        }];
    }
}

//减少按钮
- (void)reduceButtonAction:(UIButton*)sender
{
    if (number > 1 && number < 1000) {
        number -= 1;
        numberCount.text = [NSString stringWithFormat:@"%d", number];
    }
}

//增加按钮
- (void)addButtonAction:(UIButton*)sender
{
    if (number > 0 && number < 999) {
        number += 1;
        numberCount.text = [NSString stringWithFormat:@"%d", number];
    }
}

//编辑按钮
- (void)onNavigationRightButtonClicked:(UIButton*)sender
{
    SEGCreateActivityViewController* myCreateActivityDetailCtl = [[SEGCreateActivityViewController alloc] init];
    myCreateActivityDetailCtl.hidesBottomBarWhenPushed = YES;
    myCreateActivityDetailCtl.activityModel = self.activityModel;
    [self.navigationController pushViewController:myCreateActivityDetailCtl animated:YES];
}

#pragma mark - 网络请求数据处理

/**
 *  处理返回的活动详情
 *
 *  @param resultDict 结果字典
 */
- (void)dealWithActivityDetailDict:(NSDictionary*)resultDict
{
    NSString* code = [resultDict objectForKey:@"code"];

    if ([code isEqualToString:@"0"]) {
        self.activityModel = [ActivityModel initWithDictionary:resultDict[@"data"]];
        if ([[self.activityModel.issuePerson stringValue] isEqualToString:kAccountUserID]) {
            [finishBtn setTitle:NSLocalizedString(@"停止报名", nil) forState:UIControlStateNormal];
        }
        else {
            [finishBtn setTitle:NSLocalizedString(@"立即报名", nil) forState:UIControlStateNormal];
        }
        [m_tableView reloadData];
    }
    
    if ([self checkIsAttend]) { //已经报名
        footerView.hidden = YES;
        UIScreen* scr = [UIScreen mainScreen];
        m_tableView.frame = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height - kNavigationBarAndStatusBarHeight);
    }
    else {
        NSDate* endDate = [SEGUtils dateFromString:self.activityModel.endDate withFormatString:kTimeFormatStringSec];
        NSTimeInterval endTime = [endDate timeIntervalSince1970] * 1;
        NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970] * 1;
        if (endTime >= nowTime) {
            self.footerView.hidden = NO;
        }
        else {
            UIScreen* scr = [UIScreen mainScreen];
            CGRect appbounds = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height - kNavigationBarAndStatusBarHeight);
            m_tableView.frame = appbounds;
            self.footerView.hidden = YES;
        }
    }
}

/**
 *  处理验证活动参与人数网络
 *
 *  @param resultDict 结果字典
 */
- (void)dealWithCheckActivityPersonNumResult:(NSDictionary*)resultDict
{
    NSString* code = [resultDict objectForKey:@"code"];

    if ([code isEqualToString:@"0"]) {
        [self.activityRequestModel requestJoinActivityWithId:[self.activityModel.serviceId stringValue] andPersonNum:numberCount.text finished:^(id result, NSError* error) {
            [self dealWithJionActivityResult:result];
        }];
    }
    else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:[resultDict objectForKey:@"message"]
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                              otherButtonTitles:nil];
        [alert show];
    }
}

/** 处理参加活动请求结果
 *
 *
 *  @param resultDict 结果字典
 */
- (void)dealWithJionActivityResult:(NSDictionary*)resultDict
{
    NSString* code = [resultDict objectForKey:@"code"];
    if ([code isEqualToString:@"0"]) {
        footerView.hidden = YES;
        [footerView removeFromSuperview];
        UIScreen* scr = [UIScreen mainScreen];

        m_tableView.frame = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height - kNavigationBarAndStatusBarHeight);

        [m_tableView reloadData];

        UIAlertView* alear = [[UIAlertView alloc] initWithTitle:@"" message:@"报名成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alear show];
    }
    else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:[resultDict objectForKey:@"message"]
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                              otherButtonTitles:nil];
        [alert show];
    }
}

/**
 *  处理停止报名
 *
 *  @param resultDict 结果字典
 */
- (void)dealWithStopActivityResult:(NSDictionary*)resultDict
{
    NSString* code = [resultDict objectForKey:@"code"];

    if ([code isEqualToString:@"0"]) {
        footerView.hidden = YES;
        [footerView removeFromSuperview];
        UIScreen* scr = [UIScreen mainScreen];

        m_tableView.frame = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height - kNavigationBarAndStatusBarHeight);

        [m_tableView reloadData];

        UIAlertView* alear = [[UIAlertView alloc] initWithTitle:@"" message:@"停止报名成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alear show];
    }
    else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:[resultDict objectForKey:@"message"]
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                              otherButtonTitles:nil];
        [alert show];
    }
}

//是否已经报名
- (BOOL)checkIsAttend
{
    if ([self.activityModel.isAttend boolValue] || [self.activityModel.status intValue] == 4) { //已经报名
        return YES;
    }
    else {
        return NO;
    }
}

//活动是否过期
- (BOOL)checkIsStop
{
    NSDate* endDate = [SEGUtils dateFromString:self.activityModel.endDate withFormatString:kTimeFormatStringSec];
    if ([endDate compare:[NSDate date]] == NSOrderedAscending) { //过期
        return YES;
    }
    else {
        return NO;
    }
}

#pragma mark - getter
- (ActivityRequestModel*)activityRequestModel
{

    if (!_activityRequestModel) {

        _activityRequestModel = [[ActivityRequestModel alloc] init];
    }

    return _activityRequestModel;
}
@end
